package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Doream
 * @Date: 2022/2/1 21:22
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDtoListener extends AnalysisEventListener<ExcelDictDto> {

    // 因为ExcelDictDtoListener没有被spring容器管理，所以使用构造函数来传递DictMapper
    private DictMapper dictMapper;
    List<ExcelDictDto> list = new ArrayList<ExcelDictDto>();
    // 每隔5条记录，批量存储一次
    private static final int BATCH_COUNT = 5;

    @Override
    public void invoke(ExcelDictDto data, AnalysisContext analysisContext) {
        log.info("解析到一条记录: {}", data);
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 当最后剩余的数据记录不足BATCH_COUNT，最后存储一次
        if (list.size() > 0) {
            saveData();
        }
        log.info("所有数据解析完成: {}");
    }

    /**
     * 批量存储方法
     */
    private void saveData() {
        log.info("{} 条数据被存储到数据库", list.size());
        dictMapper.insertBatch(list);
        log.info("{} 条数据存储到数据库成功", list.size());
        list.clear();
    }

    public ExcelDictDtoListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }
}
